<template>
  <div v-if="is_info" v-html="value"></div>
  <div v-else class="form_item-editor">
    <textarea class="editor-inner" ref="editor" spellcheck="false" :name="name" :value="value"></textarea>
  </div>
</template>

<script>
import Editor from 's94-editor'
import hljs from 'highlight.js'

export default {
  _title_: '编辑器',
  _can_config_: true,
  _can_form_param_: true,
  name: "editor",
  props: ['name', 'value', 'config', 'is_info', 'protocol', 'select_after_callback', 'size', 'is_list'],
  emits: ['update:value', 'change'],
  data(){
    return {
      need_display: true, //是否需要渲染
    }
  },
  methods: {
    update_value(value, need_display){
      let app = this;
      if (!need_display){
        app.need_display = false;
        setTimeout(function (){app.need_display = true;},5)
      }
      this.$emit('update:value', value);
      this.$emit('change', value);
    },
    select_after(selected){
      if (typeof(this.select_after_callback) == 'function') return this.select_after_callback(selected);
      let arr = [];
      for (let i = 0; i < selected.length; i++) {
        let v = selected[i]['url'];
        if (!v) {
          this.$message.error('所选素材缺少url');
          return [];
        }
        if (this.protocol && ~['http','https'].indexOf(this.protocol)){
          v = v.replace(/^(https?:)?\/\//, this.protocol+'://')
        }
        arr.push(v)
      }
      return arr;
    },
  },
  watch: {
    value(){
      if (!this.need_display || !this.editor) return;
      setTimeout(()=>{
        this.editor.updateHtml();
        this.editor.lastRow();
      },5)
    },
  },
  mounted() {
    let app = this;
    if (this.is_info) return;
    var editor_config = {
      code_highlight: function (code, type, menu){
        var html = '<pre class="hljs"><code>' + hljs.highlight(code, {language: type}).value + '</code></pre>';
        if(!menu.editor.container.querySelector('style.hljs-style')){
          var style = document.createElement('style');
          style.className = "hljs-style";
          style.innerHTML = "pre.hljs{display:block;overflow-x:auto;padding:0.5em;color:#abb2bf;background:#282c34;}pre.hljs code{font-family: Consolas,微软雅黑,monospace;}.hljs-comment,.hljs-quote{color:#5c6370;font-style:italic}.hljs-doctag,.hljs-formula,.hljs-keyword{color:#c678dd}.hljs-deletion,.hljs-name,.hljs-section,.hljs-selector-tag,.hljs-subst{color:#e06c75}.hljs-literal{color:#56b6c2}.hljs-addition,.hljs-attribute,.hljs-meta-string,.hljs-regexp,.hljs-string{color:#98c379}.hljs-built_in,.hljs-class .hljs-title{color:#e6c07b}.hljs-attr,.hljs-number,.hljs-selector-attr,.hljs-selector-class,.hljs-selector-pseudo,.hljs-template-variable,.hljs-type,.hljs-variable{color:#d19a66}.hljs-bullet,.hljs-link,.hljs-meta,.hljs-selector-id,.hljs-symbol,.hljs-title{color:#61aeee}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:bold}.hljs-link{text-decoration:underline}";
          menu.editor.container.appendChild(style);
        }
        return html;
      },
    }
    function iframe_file(type, menu){
      let iframe_url_map = {
        all: '/file/index',
        img: '/file/index?type=jpg,jpeg,png,gif,webp',
        video: '/file/index?type=mp4',
        audio: '/file/index?type=mp3',
      };
      let action_func = {
        img(menu, url){
          menu.editor.execCommand('insertHTML', `<img src="${url}" style="max-width: 100%;">`);
        },
        video(menu, url){
          menu.editor.execCommand('insertHTML', `<video style="width: 100%;" src="${url}" autoplay="autoplay" controls="controls"></video>`);
        },
        audio(menu, url){
          menu.editor.execCommand('insertHTML', `<audio style="width: 100%;" src="${url}" autoplay="autoplay" controls="controls"></audio>`);
        },
      }
      if (!iframe_url_map[type]) return;
      app.iframe(iframe_url_map[type], {
        btns: {
          '确定_primary'(win_app){
            let arr = app.select_after(win_app.$refs['list_url'].selected);
            if (arr.length == 0) return ;
            arr.reverse().forEach(function (url){
              let ms = url.match(/\.([0-9a-z]+)(\?|$)/i);
              if (!ms) return ;
              switch (ms[1].toLowerCase()) {
                case 'jpg': case'jpeg': case'png': case'gif': case'webp': {
                  action_func['img'](menu, url);
                }break;
                case 'mp4': {
                  action_func['video'](menu, url);
                }break;
                case 'mp3': {
                  action_func['audio'](menu, url);
                }break;
              }
            })

            win_app.__iframe.show = false;
          },
        }
      })

    }
    Editor.Menu.menuList.image.title = '素材';
    Editor.Menu.menuList.image.onclick = function (menu){
      menu.showSelect([
        {innerHTML: '全部', onclick: function(menu){ iframe_file('all', menu) }},
        {innerHTML: '图片', onclick: function(menu){ iframe_file('img', menu) }},
        {innerHTML: '视频', onclick: function(menu){ iframe_file('video', menu) }},
        {innerHTML: '音频', onclick: function(menu){ iframe_file('audio', menu) }},
      ])
    }
    if (this.config){
      editor_config.menus = this.config.toString().split(',')
    }
    this.editor = new Editor(this.$refs.editor, editor_config);

    this.editor.container.addEventListener('input', function (){
      app.update_value(app.editor.html());
    });
    this.editor.textarea.addEventListener('change', function (){
      app.update_value(app.editor.html());
    });
  }
}
</script>

<style scoped>
.form_item-editor{width: 650px;padding: 04px;border-radius: 04px;border: solid 01px var(--sm_bg);outline: 0;}
.form_item-editor .editor-inner{display: block;width: 100%;height: 600px;outline: none;resize: none;overflow-y: scroll;}
.form_item-editor .editor-inner::-webkit-scrollbar{display: none;}
</style>